import Vue from 'vue';
import Vuex from 'vuex';
import {getItem, removeItem, setItem} from '@/plugins';
import {getUserInfo, homePageData, LoginApi, userRegister} from '@/api/apiFox';
import {decrypt, encrypt} from '@/utils/AES';
import order from '@/store/order';
const tokenKey = 'access_key';
const user = 'user';
const userInfo = 'userInfo';
Vue.use(Vuex);

export default new Vuex.Store({
    modules: {
        order
    },
    state: {
        isLogin:localStorage.getItem('il') || false,
        token: getItem(tokenKey),
        lang: getItem('lang') ||
            {
                langText: 'en', value: 'en', icon: require('@/assets/image/en.jpg')
            },
        User: localStorage.getItem(userInfo) || '',
        website: getItem('website') || '',
        searchHistoryArr: [],
        appName: null,
        footer: [],
        currentBalance: 0,
        favoriteProducts: JSON.parse(localStorage.getItem('favoriteProducts')) || [],
        shopCart: localStorage.getItem('shopCart')? JSON.parse(localStorage.getItem('shopCart')) : [],
    },
    getters: {
        isLogin:state => state.isLogin,
        userInfo: state => state.User,
        currentBalance: state => state.currentBalance,
        appName: state => state.appName,
        lang: state => state.lang,
        footer: state => state.footer,
        favoriteProducts: state => state.favoriteProducts
    },
    mutations: {
        SET_CURRENT_BALANCE(state, data) {
            state.currentBalance = data || 0;
        },
        setFavoriteProducts(state, data) {
            state.favoriteProducts = data;
            localStorage.setItem('favoriteProducts', JSON.stringify(state.favoriteProducts));
        },
        addFavoriteProduct(state, product) {
            const index = state.favoriteProducts.findIndex(item => item.id === product.id);
            if (index === -1) {
                state.favoriteProducts.push(product);
                localStorage.setItem('favoriteProducts', JSON.stringify(state.favoriteProducts));
            }else{
                //如果有则删除原有数据，并更新localstorage
                state.favoriteProducts.splice(index, 1);
                localStorage.setItem('favoriteProducts', JSON.stringify(state.favoriteProducts));
            }
        },
        removeFavoriteProduct(state, productId) {
            state.favoriteProducts = state.favoriteProducts.filter(product => product.id !== productId);
            localStorage.setItem('favoriteProducts', JSON.stringify(state.favoriteProducts));
        },
        getShopCart(state){
            return state.shopCart
        },
        SET_SHOP_CART(state,data){
            state.shopCart = data;
            localStorage.setItem('shopCart',JSON.stringify(data))
        },
        addShopCart(state,data){
            const index =state.shopCart.findIndex(item => item.id === data.id && item.shopId === data.shopId);
          if(index !== -1){
              state.shopCart[index].num = state.shopCart[index].num + data.num;
          }else{
              state.shopCart.push(data)
          }
            localStorage.setItem('shopCart',JSON.stringify(state.shopCart))
        },
        updateFooter(state, data) {
            state.footer = data;
        },
        // 添加搜索历史记录
        //addSearchHistory: (state,data)=>state.searchHistoryArr.push(data),
        addSearchHistory(state, data) {
            state.searchHistoryArr.push(data);
        },
        // 更新token
        saveToken(state, data) {
            state.token = data.userinfo.token;
            state.User = encrypt(JSON.stringify(data.userinfo));
            state.isLogin = true;
            localStorage.setItem('il',true);
            setItem(userInfo, encrypt(JSON.stringify(data.userinfo)));
            setItem(tokenKey, state.token);
        },
        SET_IS_LOGIN(state,bool){
            state.isLogin = bool;
            localStorage.setItem('il',bool);
        },
        updateUserInfo(state, data) {
            state.User = data.User;
            setItem(userInfo, encrypt(JSON.stringify(data.userInfo)));
            // location.reload()
        },

        updateLang(state, data) {
            state.lang = data;
        },
        setHomeState(state, data) {
            state.website = data;
            state.appName = data?.data?.web_name || null;
            document.title = state.appName || 'welcome';
            setItem('website', data.data);
        },

        removeToken(state, data) {
            state.token = '';
            state.User = '';
            removeItem(userInfo);
            removeItem(tokenKey);

        }

    },
    actions: {
        removeShopCartByIndex({ commit,state }, index) {
            let result = JSON.parse(JSON.stringify(state.shopCart))
            result.splice(index, 1);
            commit('SET_SHOP_CART',result)
        },
        clearFavoriteProducts({ commit }) {
            commit('setFavoriteProducts', []);
        },
        addFavoriteProduct({ commit,state}, product) {
            commit('addFavoriteProduct', product);
        },
        removeFavoriteProduct({ commit }, productId) {
            commit('removeFavoriteProduct', productId);
        },
        clearShopCart(state,data){
            state.shopCart = []
            localStorage.setItem('shopCart',JSON.stringify([]))
        },
        updateShopCartByIndexWithKey({ commit,state}, {index,key,value}) {
            let result = JSON.parse(JSON.stringify(state.shopCart))
            result[index][key] = value;
            commit('SET_SHOP_CART',result)
        },
        getShopCart({state}){
            return new Promise((resolve) => {
                let _shopCart = JSON.parse(JSON.stringify(state.shopCart))
                let shopCart = []
                _shopCart.forEach(item => {
                    let shopIndex = shopCart.findIndex(shop => shop.shopId === item.shopId)
                    if(shopIndex !== -1){
                        shopCart[shopIndex].goods.push(item)
                    }else{
                        shopCart.push({
                            shopId: item.shopId,
                            shopName: item.shopName,
                            goods: [item],
                            checkes:[]
                        })
                    }
                })
                resolve(shopCart)
            })
        },
        addShopCart({commit},data){
            commit('addShopCart',data)
        },
        loginSetToken({commit}, data) {
            return new Promise((resolve, reject) => {
                LoginApi(data).then(res => {
                    commit('saveToken', res);
                    resolve(res);
                }).catch(err => {
                    reject(err);
                });
            });
        },
        RegSetToken({commit}, data) {
            return new Promise((resolve, reject) => {
                userRegister(data).then(res => {
                    commit('saveToken', res);
                    resolve(res);
                }).catch(err => {
                    reject(err);
                });
            });
        },
        updateLang({commit}, data) {
            commit('updateLang', data);
        },
        removeTokenItem({commit}) {
            commit('removeToken');
        },
        updateUser({commit}, data) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    commit('updateUserInfo', res);
                    commit('SET_CURRENT_BALANCE', res?.money);
                    commit('SET_IS_LOGIN',true)
                    resolve(res);
                }).catch(err => {
                    reject(err);
                });
            });
        },
        generateFooter({commit}, footerArr) {
            function buildTree(data, parentId) {
                let tree = [];
                data.forEach(item => {
                    if (item.pid === parentId) {
                        let children = buildTree(data, item.id);
                        if (children.length) {
                            item.children = children;
                        }
                        tree.push(item);
                    }
                });
                return tree;
            }
            let footer = buildTree(footerArr, 0);
            commit('updateFooter', footer);
        },
        getHomeData({commit, dispatch}, data) {
            return new Promise((resolve, reject) => {
                homePageData().then(res => {
                    commit('setHomeState', res);
                    dispatch('generateFooter', res.data?.footer_news || []);
                    resolve(res);
                }).catch(err => {
                    reject(err);
                });
            });
        }
        // 调用例子
        // this.$store.dispatch('loginSetToken',this.submitForm).then(res=>{
        //   this.interfaceLoading=false
        //   this.$router.replace('/home/chat')
        // }).catch(err=>{
        //   this.interfaceLoading=false
        //   this.verificationCode()
        // })
    },
})
;
